import { isArray, isEmpty } from "lodash";
// 组装图表配置
export function getChartOption({ xAxisData = [], seriesData = [], chartOption = {} }) {
  // 图例
  const name = chartOption.name || [];
  const legend = chartOption.legend || { show: false };

  const lineStyle = chartOption.lineStyle;
  const itemStyle = chartOption.itemStyle;
  const markPoint = chartOption.markPoint;
  const cursor = chartOption.cursor;
  const emphasis = chartOption.emphasis;
  const markArea = chartOption.markArea;
  // 坐标轴单位
  const unit = chartOption.unit || "%";
  const yAxisLabelFormat = chartOption.yAxisLabelFormat || "{value} " + unit;
  const yAxisIndex = chartOption.yAxisIndex;

  const fixMin = chartOption.fixMin || false;
  const fixMax = chartOption.fixMax || false;
  // fixMin、fixMax打开即为最大最小值，否则则是折线最大值+-数值
  const yAxisMin = chartOption.yAxisMin || 10;
  const yAxisMax = chartOption.yAxisMax || 10;
  const type = chartOption.type || "";
  const grid = chartOption.grid || {
    top: "7%",
    left: "3%",
    right: "5%",
    bottom: "3%",
    containLabel: true
  };
  // y轴
  const yAxis = chartOption.yAxis || {
    type: "value",
    min: function(value) {
      //取最小值向下取整为最小刻度
      return fixMin ? yAxisMin : Math.floor(value.min - yAxisMin);
    },
    max: function(value) {
      //取最大值向上取整为最大刻度
      return fixMax ? yAxisMax : Math.floor(value.max + yAxisMax);
    },
    axisLabel: {
      interval: "auto",
      formatter: yAxisLabelFormat
    }
  };
  const series = seriesData.map((item, index) => {
    return Object.assign(
      { ...(name.length ? { name: name[index] } : {}) },
      {
        data: item,
        type: "line",
        showSymbol: false,
        lineStyle: lineStyle ? lineStyle[index] : {},
        itemStyle: itemStyle ? itemStyle[index] : {},
        markPoint: markPoint ? markPoint[index] : {},
        emphasis: emphasis ? emphasis[index] : {},
        cursor: cursor ? cursor[index] : {},
        yAxisIndex: yAxisIndex ? yAxisIndex[index] : 0,
        markArea: markArea
          ? {
              data: markArea[index],
              itemStyle: {
                color: "rgba(207, 30, 51, 0.3)"
              }
            }
          : {}
      }
    );
  });
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross"
      },
      formatter: function(params) {
        const customUnit = [];
        chartOption.yAxis &&
          chartOption.yAxis.map(item => {
            if (item?.axisLabel?.formatter) {
              customUnit.push(item.axisLabel.formatter.replace("{value}", ""));
            }
          });
        const tooltipDom = chartOption.tooltipDomFunc
          ? chartOption.tooltipDomFunc(params, name)
          : tooltipDomFunc(params, name, customUnit.length ? customUnit : unit);
        return tooltipDom;
      },
      // 纠正悬浮提示框部分顶部被切掉bug
      position: function(point, params, dom, rect, size) {
        // 鼠标坐标和提示框位置的参考坐标系是：以外层div的左上角那一点为原点，x轴向右，y轴向下
        // 提示框位置
        var x = 0; // x坐标位置
        var y = 0; // y坐标位置

        // 当前鼠标位置
        var pointX = point[0];
        var pointY = point[1];

        // 外层div大小
        // var viewWidth = size.viewSize[0];
        // var viewHeight = size.viewSize[1];

        // 提示框大小
        var boxWidth = size.contentSize[0];
        var boxHeight = size.contentSize[1];

        // boxWidth > pointX 说明鼠标左边放不下提示框
        if (boxWidth > pointX) {
          x = 5;
        } else {
          // 左边放的下
          x = pointX - boxWidth;
        }

        // boxHeight > pointY 说明鼠标上边放不下提示框
        if (boxHeight > pointY) {
          y = 5;
        } else {
          // 上边放得下
          y = pointY - boxHeight;
        }

        return [x, y];
      }
    },
    grid,
    legend,
    series,
    xAxis: {
      type: "category",
      axisTick: {
        alignWithLabel: true
      },
      data: xAxisData,
      width: 100,
      axisLabel: {
        show: true,
        margin: 16,
        showMaxLabel: true,
        textStyle: {
          color: "#94A5B2",
          fontSize: 12
        }
      }
    },
    yAxis
  };
  return option;
}
function tooltipDomFunc(params, name, unit) {
  let indicators = "";
  params.map((item, index) => {
    indicators += `<p>${item.marker} ${name[index] || "指标" + (index + 1)}：${(params[index]
      .data || 0) + (isArray(unit) ? unit[index] : unit)}</p>`;
  });
  return `<div>
    <p style="text-indent: 16px;">截止日期：${params[0].axisValue}</p>
    ${indicators}
    </div>`;
}

import { getAccessButtonList } from "../../api";
import { getDataSource } from "./dataSource";
/**
 * @description 判断用户是否有按钮权限
 * @author fengjunjie
 * @param {String} btnKeyMap 按钮数组，含有btnAccess(角色)和btnProp(按钮id)的数组对象
 * @return {Object} accessBtnObj 返回对应按钮权限数组，用来显示或隐藏
 */
export async function getAccessButton(btnKeyMap) {
  try {
    const accessBtn = getDataSource("setting", "accessBtn");
    const buttonRes = await getAccessButtonList({}, "get");
    const accessBtnObj = {};
    btnKeyMap.map(btnItem => {
      // 按钮存在多个角色权限
      if (btnItem.btnAccess.indexOf(",") !== -1) {
        btnItem.btnAccess.split(",").some(btnAccess => {
          const accessIds = accessBtn.find(item => item.btnKey === btnAccess) || {};
          const isAceess = buttonRes?.data?.includes(accessIds.btnId || "") ?? false;
          accessBtnObj[btnItem.btnProp] = isAceess;
          if (isAceess) return true;
        });
      } else {
        const accessIds = accessBtn.find(item => item.btnKey === btnItem.btnAccess) || {};
        accessBtnObj[btnItem.btnProp] = buttonRes?.data?.includes(accessIds.btnId || "") ?? false;
      }
    });
    return accessBtnObj;
  } catch (error) {
    console.log(error);
    return {};
  }
}

/**
 * 获取地址栏参数
 * @param {String} paramName
 * @returns
 */
export function getUrlParams(paramName) {
  // 传入数组参数键值，返回对象
  if (isArray(paramName)) {
    const params = {};
    paramName.map(name => {
      const resParam = handleUrl(name);
      resParam && (params[name] = handleUrl(name));
    });
    return isEmpty(params) ? null : params;
    // 传入字符串键值，返回字符串
  } else {
    return handleUrl(paramName);
  }
}
// 正则校验获取地址栏url的对应参数
function handleUrl(paramName) {
  const isInIframe = window.self !== window.top;
  const selfFlag = window?.location?.href?.indexOf(paramName) !== -1;
  const selfUrl = (selfFlag && window.location.href) || "/";
  const parentFlag = window?.parent?.location?.href?.indexOf(paramName) !== -1;
  const parentUrl = (parentFlag && window?.parent?.location?.href) || "/";
  const url = isInIframe ? parentUrl : selfUrl;
  let param = "";
  // 以?为分隔符切割数组取含有参数的那一段
  url.split("?").some(item => {
    if (item.indexOf(paramName) !== -1) {
      param = item;
      return true;
    }
  });
  const reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
  const r = reg.exec(param);
  if (r != null) return decodeURI(r[2]);
  return null;
}
// 把树形结构转换为普通数组
export function handleTreeArr(treeList, optionChildName='children'){
  let treeArr = []
  treeList.map(item=>{
    const filterItem = {}
    Object.keys(item).map(key=>{
      if(key!==optionChildName){
        filterItem[key] = item[key]
      }
    })
    treeArr.push(filterItem)
    if (item[optionChildName] && item[optionChildName].length) {
      treeArr = treeArr.concat(handleTreeArr(item[optionChildName], optionChildName))
      return
    }
  })
  return treeArr
}